/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import dao.LiveServersDao;
import dao.LiveServersTaskDao;
import dao.MainScheduleTaskDao;
import dao.ProviderDao;
import dao.ScheduleDataDao;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import pojo.CMST;
import pojo.LiveServers;
import pojo.MyLST;
import pojo.Provider;
import pojo.ProviderTask;

import pojo.Scheduledata;

/**
 *
 * @author javauser
 */
//class that deals with schedule task on linux
public class ScheduledTaskLinux {

    private Connection c;

    public ScheduledTaskLinux(Connection c) {
        this.c = c;
    }

    public static void main(String[] args) {
    }

    //creates schedule task on linux
    public boolean create(Scheduledata data, String providername) {
        new CustomSchTask(data, providername);
        return true;
    }

    //method to enable schedule task on linux
    public boolean enable(int taskid) {
        boolean check = false;
        try {
            ScheduleDataDao dao = new ScheduleDataDao(c);
            ProviderDao pdao=new ProviderDao(c);
            Scheduledata sdata = dao.getask(taskid);
            sdata.setIsenable(true);
            boolean enableresult = dao.update(sdata);
            if (enableresult == true) {
                check = true;
            } else {
                check = false;
            }
            Provider pro=pdao.getById(taskid);
            String file="/home/ahmed/Desktop/CronJobs";
            String lineToModify=pro.getName();
            File cronFile = new File(file);
            BufferedReader reader = new BufferedReader(new FileReader(cronFile));
            String line = "", oldtext = "",neededLine="";
            while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "\r\n";
                 if(line.trim().endsWith(lineToModify)){
                     neededLine =line;
                 }
             }
            reader.close();
            // replace a word in a file
            //String newtext = oldtext.replaceAll("drink", "Love");
            
            //To replace a line in a file
             
            String newtext = oldtext.replace(neededLine,neededLine.replace("#",""));
            
            FileWriter writer = new FileWriter("/home/ahmed/Desktop/CronJobs");
            writer.write(newtext);
            writer.close();
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
        } catch (Exception ex) {
            check = false;
            LogFile.log(" System ", " encountered the Following exception during enabling the the schedule task " + ex.getMessage());
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }

    //method to disable schedule task on linux
    public boolean disable(int taskid) {
        boolean check = false;
        try {
            ScheduleDataDao dao = new ScheduleDataDao(c);
            ProviderDao pdao=new ProviderDao(c);
            Scheduledata sdata = dao.getask(taskid);
            sdata.setIsenable(false);
            boolean enableresult = dao.update(sdata);
            if (enableresult == true) {
                check = true;
            } else {
                check = false;
            }
            Provider pro=pdao.getById(taskid);
            String file="/home/ahmed/Desktop/CronJobs";
            String lineToModify=pro.getName();
            File cronFile = new File(file);
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = "", oldtext = "",neededLine="";
            while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "\r\n";
                 if(line.trim().endsWith(lineToModify)){
                     neededLine =line;
                 }
             }
            reader.close();
            // replace a word in a file
            //String newtext = oldtext.replaceAll("drink", "Love");
            
            //To replace a line in a file
             
            String newtext = oldtext.replace(neededLine,"#"+neededLine);
            
            FileWriter writer = new FileWriter("/home/ahmed/Desktop/CronJobs");
            writer.write(newtext);
            writer.close();
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
        } catch (Exception ex) {
            check = false;
            LogFile.log(" System ", " encountered the Following exception during enabling the the schedule task " + ex.getMessage());
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }

    //method to start schedule task on linux
    public boolean start(int taskid) {
        boolean check = false;
        try {
            ProviderDao pdao = new ProviderDao(c);
            Provider provider = pdao.getById(taskid);

            ScheduleDataDao scdao = new ScheduleDataDao(c);
            Scheduledata scdata = scdao.getask(taskid);
            if (scdata.getIsenable()) {
                scdata.setIsrunning(true);
                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document config = builder.parse("/home/ahmed/NetBeansProjects/trunk/Book Dimension Project/src/java/Configuration/linconfig.xml");
                    Element pathelement = (Element) config.getElementsByTagName("jar-path").item(0);
                    Element jrePath = (Element) config.getElementsByTagName("jre-path").item(0);
                    String min = "*";
                    String hour = "*";
                    String dayOfMon = "*";
                    String mon = "*";
                    String day = "*";
                    String mod = scdata.getModifier();
                    if (Integer.parseInt(mod) > 1) {
                        String schedule = scdata.getSchedule();
                        if (schedule.equalsIgnoreCase("hourly")) {
                            hour = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("daily")) {
                            dayOfMon = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("weekly")) {
                            day = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("monthly")) {
                            mon = "*/" + mod;
                        }
                    }
                    FileOutputStream fos = null;
                    String taskTime = jrePath.getTextContent().trim() + "/bin/java -jar " + pathelement.getTextContent().trim() + "  " + provider.getName() + " " + "\n ";
                    String fileName = "/home/ahmed/Desktop/AtJobs";
                    File file = new File(fileName);
                    fos = new FileOutputStream(file);
                    fos.write(taskTime.getBytes());
                    fos.close();
                    String task = "at -f" + fileName + " now";
                    file = new File("/home/ahmed/Desktop/AtExecuter.sh");
                    fos = new FileOutputStream(file);
                    fos.write(task.getBytes());
                    fos.close();
                    Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/AtExecuter.sh");
                    Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/AtExecuter.sh");
                    LogFile.log("System", "creates Schedule Task for provider " + provider.getName() + " and that schedule task will run every " + scdata.getModifier() + " " + scdata.getSchedule() + " at " + scdata.getStartTime() + " starting from " + scdata.getStartDate());
                } catch (SAXException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to create the schedule task for provider " + provider.getName() + " this may be due to : " + ex.getMessage());
                } catch (IOException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to create the schedule task for provider " + provider.getName() + " this may be due to : " + ex.getMessage());
                } catch (ParserConfigurationException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to create the schedule task for provider " + provider.getName() + " this may be due to : " + ex.getMessage());
                }
                boolean updateresult = scdao.update(scdata);
                if (updateresult == true) {
                    check = true;
                } else {
                    check = false;
                }
            } else {
                check = false;
                System.out.println("Schedule Task is Disabled Please Enable it First.");
                LogFile.log(" System ", " encountered that  this  schedule task is Disabled ");
            }
        } catch (Exception ex) {
            check = false;
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System ", " encountered the following exception while trying to start the schedule task " + ex.getMessage());
        }
        return check;
    }
    
    //method to end running schedule task
    public boolean end(int taskid)
    {
        boolean check=false;
        Provider provider=null;
        try {
            ScheduleDataDao dao = new ScheduleDataDao(c);
            Scheduledata scdata=dao.getask(taskid);
            scdata.setIsrunning(false);
            check=dao.update(scdata);
            
            ProviderDao pdao=new ProviderDao(c);
            provider= pdao.getById(taskid);
            }
        catch (Exception ex){
            check=false;
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System ", " encountered the following exception while trying to end the schedule task of the provider "+provider.getName()+" and this is the exception error "+ex.getMessage());
            }
        return check;
    }
    
    //method to delete schedule task on linux
    public boolean delete(int taskid) {
        boolean check=true;
        Provider provider=null;
        ProviderDao pdao=new ProviderDao(c);
        ScheduleDataDao dao = new ScheduleDataDao(c);
        try {
            provider= pdao.getById(taskid);
            RemoveCronJob rcj=new RemoveCronJob();
            System.out.println("Provider Name is : "+provider.getName());
            String providerName=provider.getName();
            rcj.removeLineFromFile("/home/ahmed/Desktop/CronJobs",providerName);
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
            System.out.println("Delete Operation Done Successfully");
            }
            catch (Exception ex){
                check=false;
                Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
                LogFile.log(" System ", " encountered the following exception while trying to end the schedule task of the provider "+provider.getName()+" and this is the exception error "+ex.getMessage());
            }
        return check;
    }

    //method to create main schedule task on linux
    public boolean createmaintask(CMST cmst, String taskType) {
        
        new MainTaskLinux(cmst, taskType);
        return true;
    }

    //method to create live server task on linux
    public boolean  createLiveServerTask(MyLST lst, LiveServers ls) {
        String LSObject = ls.getType() + "-" + ls.getIp() + "-" + ls.getPort() + "-" + ls.getUserName() + "-" + ls.getPassword();
        new LiveServerLinuxTask(lst, LSObject, ls.getIp());
        return true;
    }

    //method to delete live server task on linux
    public boolean deleteLiveServerTask(Integer lstId) {
        boolean check=true;
        LiveServers ls=null;
        LiveServersDao lsd=new LiveServersDao(c);
        try {
            ls= lsd.getById(lstId);
            RemoveCronJob rcj=new RemoveCronJob();
            String LSObject=ls.getType()+"-"+ls.getIp()+"-"+ls.getPort()+"-"+ls.getUserName()+"-"+ls.getPassword();
            rcj.removeLineFromFile("/home/ahmed/Desktop/CronJobs",LSObject);
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
            System.out.println("Delete Operation Done Successfully");
            }
            catch (Exception ex){
                check=false;
                Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
                LogFile.log(" System ", " encountered the following exception while trying to delete the schedule task of the Server "+ls.getIp()+" and this is the exception error "+ex.getMessage());
            }
        return check;
    }

    //method to delete main task on linux
    public boolean deleteMainTask(String taskName) {
        boolean check=true;
        MainScheduleTaskDao mstdao=new MainScheduleTaskDao(c);
        CMST cmst=null;
        try {
            cmst=mstdao.getask(taskName);
            RemoveCronJob rcj=new RemoveCronJob();
            System.out.println("Task Type is : "+cmst.getTaskType());
            String taskType=cmst.getTaskType();
            rcj.removeLineFromFile("/home/ahmed/Desktop/CronJobs",taskType);
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
            System.out.println("Delete Operation Done Successfully");
            }
            catch (Exception ex){
                check=false;
                //Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
                LogFile.log(" System ", " encountered the following exception while trying to delete schedule task With Name "+cmst.getTaskName()+" and this is the exception error "+ex.getMessage());
            }
        return check;
    }

    //method to return all provider tasks
    public Vector<Scheduledata> getAllTasks() {
        try 
        {
            ScheduleDataDao dao = new ScheduleDataDao(c);
            return dao.getall();
        } 
        catch (Exception ex)
        {
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System "," encountered the following Exception while trying to display all available schedule tasks "+ex.getMessage());
        }
        return null;
    }

    public Vector<Provider> getAllProviders() {
        try 
        {
            ProviderDao dao = new ProviderDao(c);
            return dao.getAll();
        } 
        catch (Exception ex)
        {
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System "," encountered the following Exception while trying to display all available schedule tasks "+ex.getMessage());
        }
        return null; 
    }
    
    
    //method to get all provider Names and tasks
    public Vector<ProviderTask> getAllProviderTasks()
    {
        Vector<ProviderTask> prtsvect=new Vector<ProviderTask>();
        try{
            ScheduleDataDao scdao=new ScheduleDataDao(c);
            Vector<Scheduledata> scdata=scdao.getall();
            ProviderDao prdao=new ProviderDao(c);
            Vector<Provider> prdata=prdao.getAll();
            System.out.println("Number Of Providers is : "+prdata.size());
            System.out.println("Number Of Schedule Tasks is : "+scdata.size());
            for(int i=0 ; i<prdata.size() ; i++){
                ProviderTask prts=new ProviderTask();
                    System.out.println("Hello Condition occured");
                    prts.setpId(prdata.elementAt(i).getPId());
                    prts.setName(prdata.elementAt(i).getName());
                    prts.setScId(scdata.elementAt(i).getScId());
                    prts.setSchedule(scdata.elementAt(i).getSchedule());
                    prts.setModifier(scdata.elementAt(i).getModifier());
                    prts.setStartDate(scdata.elementAt(i).getStartDate());
                    prts.setStartTime(scdata.elementAt(i).getStartTime());
                    prts.setDay(scdata.elementAt(i).getDay());
                    prts.setIsenable(scdata.elementAt(i).getIsenable());
                    prts.setIsrunning(scdata.elementAt(i).getIsrunning());
                    prts.setMonth(scdata.elementAt(i).getMonth());
                    prtsvect.add(prts);
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        System.out.println("Vector Size is : "+prtsvect.size());
        return prtsvect;
    }

    //method to enable main task
    public boolean enableMainTask(String taskName) {
        boolean check = false;
        try {
            MainScheduleTaskDao mstdao=new MainScheduleTaskDao(c); 
            CMST cmst= mstdao.getask(taskName);
            cmst.setIsEnable(true);
            boolean enableresult = mstdao.update(cmst);
            if (enableresult == true) {
                check = true;
            } else {
                check = false;
            }
            String file="/home/ahmed/Desktop/CronJobs";
            String lineToModify=cmst.getTaskType();
            File cronFile = new File(file);
            BufferedReader reader = new BufferedReader(new FileReader(cronFile));
            String line = "", oldtext = "",neededLine="";
            while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "\r\n";
                 if(line.trim().endsWith(lineToModify)){
                     neededLine =line;
                 }
             }
            reader.close();
            // replace a word in a file
            //String newtext = oldtext.replaceAll("drink", "Love");
            
            //To replace a line in a file
             
            String newtext = oldtext.replace(neededLine,neededLine.replace("#",""));
            
            FileWriter writer = new FileWriter("/home/ahmed/Desktop/CronJobs");
            writer.write(newtext);
            writer.close();
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
        } catch (Exception ex) {
            check = false;
            LogFile.log(" System ", " encountered the Following exception during enabling the the schedule task " + ex.getMessage());
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }

    //method to disable main schedule 
    public boolean disableMainTask(String taskName) {
        boolean check = false;
        try {
            System.out.println("Task Name is : "+taskName);
            MainScheduleTaskDao mstdao=new MainScheduleTaskDao(c); 
            CMST cmst= mstdao.getask(taskName);
            System.out.println("task Name from Database is : "+cmst.getTaskName());
            System.out.println("task status from Database is : "+cmst.getIsEnable());
            System.out.println("task run from Database is : "+cmst.getIsRunning());
            System.out.println("Task Type is from Database : "+cmst.getTaskType());
            cmst.setIsEnable(false);
            cmst.setIsRunning(false);
            boolean disableresult = mstdao.update(cmst);
            if (disableresult == true) {
                check = true;
            } else {
                check = false;
            }
            System.out.println("task Name from Database is after update : "+cmst.getTaskName());
            System.out.println("task status from Database is after update : "+cmst.getIsEnable());
            System.out.println("task run from Database is after update : "+cmst.getIsRunning());
            System.out.println("Task Type is after update : "+cmst.getTaskType());
            String file="/home/ahmed/Desktop/CronJobs";
            String lineToModify=cmst.getTaskType();
            File cronFile = new File(file);
            BufferedReader reader = new BufferedReader(new FileReader(cronFile));
            String line = "", oldtext = "",neededLine="";
            while((line = reader.readLine()) != null && line.length() != 0)
                 {
                 oldtext += line + "\r\n";
                 if(line.trim().endsWith(lineToModify)){
                     neededLine =line;
                 }
             }
            reader.close();
            // replace a word in a file
            //String newtext = oldtext.replaceAll("drink", "Love");
            
            //To replace a line in a file
             
            String newtext = oldtext.replace(neededLine,"#"+neededLine);
            FileWriter writer = new FileWriter("/home/ahmed/Desktop/CronJobs");
            writer.write(newtext);
            writer.close();
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
        } catch (Exception ex) {
            check = false;
            LogFile.log(" System ", " encountered the Following exception during enabling the the schedule task " + ex.getMessage());
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }

    //method to start main task on linux
    public boolean startMainTask(String taskName) {
        boolean check = false;
        MainScheduleTaskDao mstdao=new MainScheduleTaskDao(c);
        CMST cmst=mstdao.getask(taskName);
        try {
            if (cmst.getIsEnable()) {
                cmst.setIsRunning(true);
                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document config = builder.parse("/home/ahmed/NetBeansProjects/trunk/Book Dimension Project/src/java/Configuration/linconfig.xml");
                    Element pathelement = (Element) config.getElementsByTagName("main-task-jar").item(0);
                    Element jrePath = (Element) config.getElementsByTagName("jre-path").item(0);
                    String min = "*";
                    String hour = "*";
                    String dayOfMon = "*";
                    String mon = "*";
                    String day = "*";
                    String mod = cmst.getModifier();
                    if (Integer.parseInt(mod) > 1) {
                        String schedule = cmst.getSchedule();
                        if (schedule.equalsIgnoreCase("hourly")) {
                            hour = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("daily")) {
                            dayOfMon = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("weekly")) {
                            day = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("monthly")) {
                            mon = "*/" + mod;
                        }
                    }
                    FileOutputStream fos = null;
                    String taskTime = jrePath.getTextContent().trim() + "/bin/java -jar " + pathelement.getTextContent().trim() + "  " + cmst.getTaskType() + " " + "\n ";
                    String fileName = "/home/ahmed/Desktop/AtJobs";
                    File file = new File(fileName);
                    fos = new FileOutputStream(file);
                    fos.write(taskTime.getBytes());
                    fos.close();
                    String task = "at -f" + fileName + " now";
                    file = new File("/home/ahmed/Desktop/AtExecuter.sh");
                    fos = new FileOutputStream(file);
                    fos.write(task.getBytes());
                    fos.close();
                    Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/AtExecuter.sh");
                    Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/AtExecuter.sh");
                    LogFile.log("System", "started Schedule Task with Name : " + cmst.getTaskName());
                } catch (SAXException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to Start the schedule task With Name " + cmst.getTaskName()+ " this may be due to : " + ex.getMessage());
                } catch (IOException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to start the schedule task with Name " + cmst.getTaskName() + " this may be due to : " + ex.getMessage());
                } catch (ParserConfigurationException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to start the schedule task with Name " + taskName + " this may be due to : " + ex.getMessage());
                }
                boolean updateresult = mstdao.update(cmst);
                if (updateresult == true) {
                    check = true;
                } else {
                    check = false;
                }
            } else {
                check = false;
                System.out.println("Schedule Task is Disabled Please Enable it First.");
                LogFile.log(" System ", " encountered that  this  schedule task is Disabled ");
            }
        } catch (Exception ex) {
            check = false;
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System ", " encountered the following exception while trying to start the schedule task " + ex.getMessage());
        }
        return check;
    }

    //method to start live Server task
    public boolean startLiveServerTask(String serverIP) {
        boolean check = false;
        LiveServersDao lsd=new LiveServersDao(c);
        LiveServers ls=lsd.getByIp(serverIP);
        System.out.println("live Server ID : "+ls.getLsId());
        System.out.println("Live Server Port : "+ls.getPort());
        LiveServersTaskDao lstd=new LiveServersTaskDao(c);
        MyLST lst=lstd.getById(ls.getLsId());
        System.out.println("Live Server Task Status : "+lst.getIsEnable());
        String LSObject=ls.getType()+"-"+ls.getIp()+"-"+ls.getPort()+"-"+ls.getUserName()+"-"+ls.getPassword();
        try {
            if (lst.getIsEnable()) {
                lst.setIsRunning(true);
                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document config = builder.parse("/home/ahmed/NetBeansProjects/trunk/Book Dimension Project/src/java/Configuration/linconfig.xml");
                    Element pathelement = (Element) config.getElementsByTagName("live-server-jar").item(0);
                    Element jrePath = (Element) config.getElementsByTagName("jre-path").item(0);
                    String min = "*";
                    String hour = "*";
                    String dayOfMon = "*";
                    String mon = "*";
                    String day = "*";
                    String mod = lst.getModifier();
                    if (Integer.parseInt(mod) > 1) {
                        String schedule = lst.getSchedule();
                        if (schedule.equalsIgnoreCase("hourly")) {
                            hour = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("daily")) {
                            dayOfMon = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("weekly")) {
                            day = "*/" + mod;
                        } else if (schedule.equalsIgnoreCase("monthly")) {
                            mon = "*/" + mod;
                        }
                    }
                    FileOutputStream fos = null;
                    String taskTime = jrePath.getTextContent().trim() + "/bin/java -jar " + pathelement.getTextContent().trim() + "  " + LSObject + " " + "\n ";
                    String fileName = "/home/ahmed/Desktop/AtJobs";
                    File file = new File(fileName);
                    fos = new FileOutputStream(file);
                    fos.write(taskTime.getBytes());
                    fos.close();
                    String task = "at -f" + fileName + " now";
                    file = new File("/home/ahmed/Desktop/AtExecuter.sh");
                    fos = new FileOutputStream(file);
                    fos.write(task.getBytes());
                    fos.close();
                    Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/AtExecuter.sh");
                    Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/AtExecuter.sh");
                    LogFile.log("System", "started Schedule Task for IP : " + serverIP);
                } catch (SAXException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to Start the schedule task For IP : " + serverIP+ " this may be due to : " + ex.getMessage());
                } catch (IOException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to start the schedule task For IP : " + serverIP + " this may be due to : " + ex.getMessage());
                } catch (ParserConfigurationException ex) {
                    check = false;
                    Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
                    LogFile.log("System", "failed to start the schedule task For IP : " + serverIP + " this may be due to : " + ex.getMessage());
                }
                boolean updateresult = lstd.update(lst);
                if (updateresult == true) {
                    check = true;
                } else {
                    check = false;
                }
            } else {
                check = false;
                System.out.println("Schedule Task is Disabled Please Enable it First.");
                LogFile.log(" System ", " encountered that  this  schedule task is Disabled ");
            }
        } catch (Exception ex) {
            check = false;
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System ", " encountered the following exception while trying to start the schedule task " + ex.getMessage());
        }
        return check;
    }

    //method to enable live server task
    public boolean enableLiveServerTask(String ip) {
        boolean check = false;
        LiveServersDao lsd=new LiveServersDao(c);
        LiveServers ls=lsd.getByIp(ip);
        LiveServersTaskDao lstd=new LiveServersTaskDao(c);
        MyLST lst=lstd.getById(ls.getLsId());
        String LSObject=ls.getType()+"-"+ls.getIp()+"-"+ls.getPort()+"-"+ls.getUserName()+"-"+ls.getPassword();
        try {
            lst.setIsEnable(true);
            boolean enableresult = lstd.update(lst);
            if (enableresult == true) {
                check = true;
            } else {
                check = false;
            }
            String file="/home/ahmed/Desktop/CronJobs";
            String lineToModify=LSObject;
            File cronFile = new File(file);
            BufferedReader reader = new BufferedReader(new FileReader(cronFile));
            String line = "", oldtext = "",neededLine="";
            while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "\r\n";
                 if(line.trim().endsWith(lineToModify)){
                     neededLine =line;
                 }
             }
            reader.close();
            // replace a word in a file
            //String newtext = oldtext.replaceAll("drink", "Love");
            
            //To replace a line in a file
             
            String newtext = oldtext.replace(neededLine,neededLine.replace("#",""));
            
            FileWriter writer = new FileWriter("/home/ahmed/Desktop/CronJobs");
            writer.write(newtext);
            writer.close();
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
        } catch (Exception ex) {
            check = false;
            LogFile.log(" System ", " encountered the Following exception during enabling the the schedule task " + ex.getMessage());
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }

    //method to disable Live Server task
    public boolean disableLiveServerTask(String ip) {
        boolean check = false;
        LiveServersDao lsd=new LiveServersDao(c);
        LiveServers ls=lsd.getByIp(ip);
        LiveServersTaskDao lstd=new LiveServersTaskDao(c);
        MyLST lst=lstd.getById(ls.getLsId());
        String LSObject=ls.getType()+"-"+ls.getIp()+"-"+ls.getPort()+"-"+ls.getUserName()+"-"+ls.getPassword();
        try {
            lst.setIsEnable(false);
            lst.setIsRunning(false);
            boolean enableresult = lstd.update(lst);
            if (enableresult == true) {
                check = true;
            } else {
                check = false;
            }
            String file="/home/ahmed/Desktop/CronJobs";
            String lineToModify=LSObject;
            File cronFile = new File(file);
            BufferedReader reader = new BufferedReader(new FileReader(cronFile));
            String line = "", oldtext = "",neededLine="";
            while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "\r\n";
                 if(line.trim().endsWith(lineToModify)){
                     neededLine =line;
                 }
             }
            reader.close();
            // replace a word in a file
            //String newtext = oldtext.replaceAll("drink", "Love");
            
            //To replace a line in a file
             
            String newtext = oldtext.replace(neededLine,"#"+neededLine);
            
            FileWriter writer = new FileWriter("/home/ahmed/Desktop/CronJobs");
            writer.write(newtext);
            writer.close();
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
        } catch (Exception ex) {
            check = false;
            LogFile.log(" System ", " encountered the Following exception during enabling the the schedule task " + ex.getMessage());
            Logger.getLogger(ScheduledTaskWindows.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }
}
